
export const initVNode = (vnode) => {
    // 构建虚拟 dom 树
    const { vtype } = vnode
    if (vtype === undefined) {
        // 文本节点
        return document.createTextNode(vnode)
    } else if (vtype === 1) {
        // dom 
        return createElement(vnode)
    } else if (vtype === 2) {
        // 函数组件
        return createClassComp(vnode)
    } else if (vtype === 3) {
        // 类组件 classComp
        return createFunctionComp(vnode)
    }
}

const createElement = (vnode) => {
    const { type, props } = vnode
    const node = document.createElement(type)

    // 属性处理
    const { key, children, ...rest } = props
    // className
    Object.keys(rest).forEach(attr => {
        if (attr === 'className') {
            node.setAttribute('class', rest[attr])
        } else {
            node.setAttribute(attr, rest[attr])
        }
    })

    children.forEach(c => {
        node.appendChild(initVNode(c))
    })

    return node
}

const createFunctionComp = (vnode) => {
    const { type, props } = vnode
    return initVNode(type(props))
}

const createClassComp = (vnode) => {
    const { type, props } = vnode
    const component = new type(props);
    var newNode = component.render()
    return initVNode(newNode)
}

export const createVNode = (vtype, type, props) => {
    return {
        vtype, type, props
    }
}

export default {
    initVNode,
    createVNode
}